import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Dialog, DialogTitle, DialogContent, Button } from '@mui/material';

const AddNewPopulationDialog = ({ open, onClose, fetchData }) => {
    const [pname, setPname] = useState("");
    const [comment, setComment] = useState("");
    const [startdate, setStartDate] = useState(new Date());
    const [endDate, setEndDate] = useState("");
    const [pcode, setCode] = useState("12")
    const [startMass, setStartMass] = useState(0)
    const [startAllMass, setStartAllMass] = useState(0)
    const [startSize, setStartSize] = useState(0)
    const [startAmount, setStartAmount] = useState(0)
    const [equipments, setEquipments] = useState([]);
    const [equipmentId, setEquipmentId] = useState(0);

    const handleInputChange = (setter) => (event) => {
        setter(event.target.value);
    };

    useEffect(()=>{
        const headers = {
            'Authorization': `Bearer ${localStorage.getItem('access')}`,
        };
        axios.get(`${process.env.REACT_APP_API_BASE_URL}/code`,  {headers}).then((response)=>{
            setCode(response.data.code)
        })
        fetchEquipments();
    }, [open])

    

    const handlePnameChange = (event) => {
        setPname(event.target.value);
    };
    const handleComment = (event) => {
        setComment(event.target.value);
    };

    const handleStartDateChange = (event) => {
        setStartDate(event.target.value);
    };

    const handleStartMass = (event) => {
        setStartMass(event.target.value);
        setStartAllMass(event.target.value*startAmount)
    };
    const handleStartAllMass = (event) => {
        setStartAllMass(event.target.value);
    };
    const handleStartSize = (event) => {
        setStartSize(event.target.value);
    };

    const handleStartAmount = (event) => {
        setStartAmount(event.target.value);
        setStartAllMass(event.target.value*startMass)
    };
    const fetchEquipments = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/equipment?free=true`, {headers});
            setEquipments(response.data.equipments);
            setEquipmentId(response.data.equipments[0].eid)
        } catch (error) {
            console.error('Error fetching equipments:', error);
        }
    };


    const addPopulation = async () => {
        try {
            const newPopulation = {
                pcode,
                pname,
                startdate,
                avg_start_mass: startMass,
                avg_start_size: startSize,
                start_count: startAmount,
                comment,
                equipment_id: equipmentId,
            };
    
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
    
            const response = await axios.post(`${process.env.REACT_APP_API_BASE_URL}/population`, newPopulation, { headers });
                fetchData();
            onClose();
        } catch (error) {
            console.error('Error adding new population:', error);
        }
    };
    

    return (
        <Dialog open={open} onClose={onClose} sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none' } }}>
            <DialogTitle>Добавить новую популяцию</DialogTitle>
            <DialogContent>
            <div className='input-table-container'>
                       <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Код популяции</label>
                            <input
                                className='input-form-table'
                                type="text"
                                value={pcode}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                disabled={true}
                            />
                            <label>Название популяции</label>
                            <input
                                className='input-form-table'
                                type="text"
                                value={pname}
                                onChange={handlePnameChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                required={true}
                            />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Дата начала</label>
                            <input
                                className='input-form-table'
                                type="date"
                                value={startdate}
                                onChange={handleStartDateChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                required
                            />
                            <label>Дата окончания</label>
                            <input
                                className='input-form-table'
                                type="text"
                                value={endDate}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                disabled={true}
                            />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>                            <label>Средняя стартовая масса особи, грамм</label>
                            <input
                                className='input-form-table'
                                type="number"
                                value={startMass}
                                onChange={handleStartMass}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                required
                            />
                            <label>Средний стартовый размер особи, см</label>
                            <input
                                className='input-form-table'
                                type="number"
                                value={startSize}
                                onChange={handleStartSize}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                required
                            />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Стартовое количество особей, штук</label>
                            <input
                                className='input-form-table'
                                type="number"
                                value={startAmount}
                                onChange={handleStartAmount}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                required
                            />
                             <label>Стартовая масса популяции, кг</label>
                            <input
                                className='input-form-table'
                                type="number"
                                value={startAllMass}
                                onChange={handleStartAllMass}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                required
                            />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Бассейн 1</label>
                            <select
                                value={equipmentId}
                                onChange={handleInputChange(setEquipmentId)}
                                className="input-form-table"
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                {equipments.map(equipment => (
                                    <option key={equipment.eid} value={equipment.eid}>{equipment.ename}</option>
                                ))}
                            </select>
                            </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.2fr 1fr", gap: '10px' }}>
                            <label>Комментарий</label>
                            <textarea
                                className='input-form-table'
                                type="text"
                                value={comment}
                                onChange={handleComment}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%', maxWidth: '1400px' }}
                                required={true}
                            />
                        </div>
                    </div>
                <Button
                        onClick={addPopulation}
                        sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }}
                        variant={'contained'}
                        disabled={!(pname && startdate && pcode && startMass && startAllMass && startSize && startAmount && equipmentId)}
                    >
                        Сохранить
                    </Button>
            </DialogContent>
        </Dialog>
    );
};

export default AddNewPopulationDialog;
